package cn.bytecollege.admin.filter;

import cn.bytecollege.admin.service.ClassifyService;
import cn.bytecollege.admin.service.ProductService;
import cn.bytecollege.common.entity.Classify;
import cn.bytecollege.common.entity.Product;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebFilter(filterName = "ProductSaveFilter",servletNames = {"ProductSaveController","ProductUpdateController"})
public class ProductSaveFilter implements Filter {

    private ProductService productService = null;
    private ClassifyService classifyService = null;
    public ProductSaveFilter(){
        productService = new ProductService();
        classifyService = new ClassifyService();
    }
    String msg = "";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //固定操作
        HttpServletRequest req = (HttpServletRequest) request;
        //获取controller里的方法
        String method = req.getMethod();
        //获取详细的请求地址
        String uri = req.getRequestURI();
        //只过滤post请求
        if (method.equalsIgnoreCase("post")){
            //这是对增加商品
            if (uri.contains("saveProduct")){
                //定义一个方法，判断输入是否为空。
                //调用方法，if里面为true才执行
                if (!isValid(request,response)){
                    return;
                }
            }
            //这是对更改商品
            else if(uri.contains("updateProduct")) {
                if (!isValid(request, response)) {
                    return;
                }
            }
            chain.doFilter(request, response);
            return;
        }
        else {
            chain.doFilter(request, response);
        }
    }

    /**
     * 判断输入的各个参数是否为空。
     * @param request
     * @param response
     * @return
     */
    public boolean isValid(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        //固定写法
        HttpServletRequest req = (HttpServletRequest) request;
        //接收请求参数
        String classifyId = req.getParameter("classify");
        String productName = req.getParameter("productName");
        //商品数量 int
        String productNumber = req.getParameter("productNumber");
        //商品价格 float
        String productPrice = req.getParameter("productPrice");
        //商品图片
        String productPicture = req.getParameter("poster");
        //商品详情
        String productParticulars = req.getParameter("productParticulars");

        if (classifyId==null ||classifyId.equals("")){
            msg = "商品类别不能为空！";
            forward(request,response);
            return false;
        }
        if (productName==null ||productName.equals("")){
            msg = "商品名称不能为空！";
            forward(request,response);
            return false;
        }
        if (productNumber==null ||productNumber.equals("")){
            msg = "商品数量不能为空，至少一个！";
            forward(request,response);
            return false;
        }
        //验证只能输入正整数
        Pattern patternProductNumber = Pattern.compile("(^[0-9]*[1-9][0-9]*$)"); //写正则表达式
        Matcher matcherProductNumber = patternProductNumber.matcher(productNumber);
        boolean rsProductNumber = matcherProductNumber.matches();
        if (!rsProductNumber){
            msg = "商品数量请输入正整数！";
            forward(request,response);
            return false;
        }
        if (productPrice==null ||productPrice.equals("")){
            msg = "商品价格不能为空！";
            forward(request,response);
            return false;
        }
        //验证只能输入正数
        Pattern patternProductPrice = Pattern.compile("(^[0-9]+(\\.[0-9]{2})?$)"); //写正则表达式
        Matcher matcherProductPrice = patternProductPrice.matcher(productPrice);
        boolean rsProductPrice = matcherProductPrice.matches();
        if (!rsProductPrice){
            msg = "商品价格只能是0或者正整数或者正数带小数点后两位";
            forward(request,response);
            return false;
        }
        //验证用户图片。
        if (productPicture!=null &&!productPicture.equals("")){
            //不为空，进来
            if (!isPhotoFile(request,response)){
                //不是图片
                return false;
            }
            return true;
        }
        else if(productPicture!=null ||productPicture.equals("")){
            msg = "商品图片不能为空！";
            forward(request,response);
            return false;
        }

        if (productParticulars==null ||productParticulars.equals("")){
            msg = "商品详情不能为空！";
            forward(request,response);
            return false;
        }
        return true;
    }

    /**
     * 向前台显示有哪些商品分类.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        List<Classify> list = classifyService.findClassify();
        request.setAttribute("list",list);
        request.setAttribute("msg",msg);
        request.getRequestDispatcher("/admin/html/device/productSave.jsp").forward(request,response);
    }

    /**
     * 判断是不是文件格式，防止系统被上传木马导致感染病毒。
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public boolean isPhotoFile(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String posterName = req.getParameter("poster");
        System.out.println(posterName);
        //Part part = req.getPart("poster");(part不能用了，很生气。)
        //获取文件名
       // String name = part.getSubmittedFileName();
        //System.out.println(name);
        //获取扩展名
        String ext = posterName.substring(posterName.indexOf(".")+1);
        //System.out.println(ext);
        List<String> list = new ArrayList<>(7);
        list.add("jpg");
        list.add("png");
        list.add("jpeg");
        list.add("bmp");
        list.add("psd");
        list.add("pdd");
        list.add("pdf");
        //判断文件上传格式
        if (!list.contains(ext)){
            msg = "警告：不允许上传不是图片格式的文件！";
            forward(request, response); //我去，忘记了这一行，居然久久的报错，丢了。
            return false;
        }
//        Long size = part.getSize();
//        //规定大小
//        long provision = 100*1024*1024; //1*1024*1024=1MB,
//        if (size>provision){
//            String msg = "上传文件超出100MB,请重新上传";
//            return false;
//        }
        return true;
    }

    @Override
    public void destroy() {
    }
}
